package org.swim.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.swim.remote.exceptions.SwimException;
import org.swim.remote.exceptions.SwimException.Severity;
import org.swim.web.servlet.consts.Action;
import org.swim.web.utils.SwimConst;
import org.swim.web.utils.SwimUtils;

/**
 * Servlet implementation class HomeSL
 */
public class HomeSL extends SwimServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doRequest(HttpServletRequest request,
			HttpServletResponse response,
			org.swim.web.servlet.SwimServlet.Method method, Action action)
			throws ServletException, IOException {
		switch (action) {
		case REMOVEACCOUNT:
			try {
				removeAccount(request, response);
				request.getSession().invalidate();
			} catch (SwimException e) {
				e.printStackTrace();
				response.sendRedirect(SwimConst.Url.HOME);
			}
			break;

		default:
			if (SwimUtils.isLogged(request))
				response.sendRedirect(SwimConst.Url.Servlet.COLLABORATION);
			else
				response.sendRedirect(SwimConst.Url.HOME);
			break;
		}

	}

	private void removeAccount(HttpServletRequest request,
			HttpServletResponse response) throws SwimException, IOException {

		JSONObject object = new JSONObject();
		object.accumulate("token", getToken(request));
		if (!request.getParameterMap().containsKey("password"))
			throw new SwimException(
					"You can't remove account if you don't type password!",
					Severity.FATAL_ERROR);
		String password = request.getParameter("password");
		object.accumulate("password", password);
		getUmr().removeAccount(object);

		response.sendRedirect(SwimConst.Url.HOME);

	}

}
